package com.msmall.base.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.msmall.base.message.FieldError;
import com.msmall.base.message.Message;
import com.msmall.base.message.MessageManager;
import com.msmall.base.pager.PaginationFactory;
import com.msmall.base.pager.PaginationSupport;
import com.msmall.base.util.Constants;
import com.msmall.community.ApplicationManager;
import com.msmall.community.common.OnlineUser;
import com.msmall.community.common.listener.UserAgentBean;
import com.msmall.community.user.model.UserInfo;
import com.msmall.community.user.model.UserProfile;
import com.msmall.community.user.service.UserManager;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class BaseAction extends ActionSupport implements Preparable{
	
    private static final long serialVersionUID = 3525445612504421307L;
    
    protected final Log log = LogFactory.getLog(getClass());
    
    public static final String SESSION_MESSAGE_KEY = "SESSION_MESSAGE_KEY";

    public static final String CANCEL = "cancel";
    
    protected boolean isLogin;
    
    protected String pi; // 分页信息 currentIndex_pageSize
    
    protected String gotoUrl;
    
    protected Long userid;
    
    protected Long usr; // 被访问者的用户ID
    
    protected String nickname; //当前登录系统的用户昵称
    
    protected String userAgentType; //当前登录系统的用户名
    
    protected String message; // mostly used for ajax
    
    protected Integer direct;//有翻页时，表示向前/向后 例如：查看图片时 ConstantDB.DIRECTION_PREVIOUS/NEXT
	
    protected boolean isOwner = false;//进入此空间的是否是空间主人
    
    protected UserInfo userInfo; // 用户基本信息
	
    protected UserProfile userProfile; // 用户扩展基本信息
    
	protected UserAgentBean userAgentBean;
	
	protected OnlineUser onlineUser;
	
	protected PaginationSupport page;
    /**
     * Simple method that returns "cancel" result
     * @return "cancel"
     */
    public String cancel() {
        return CANCEL;
    }

	public void prepare() throws Exception {
		this.setUserid((Long) getSession().getAttribute(Constants.SESSION_USER_ID_KEY));
		this.setOnlineUser(OnlineUser.getOnlineUsers().get(userid));
		this.setUserAgentBean(this.onlineUser.getUserAgentBean());
		this.setUserAgentType(this.userAgentBean.getUserAgentType());
		
		if(message == null){
			message = (String) getFromSession(SESSION_MESSAGE_KEY);
			if(message!= null && getText("common.authentication.anonymous").equalsIgnoreCase(message)){
				if(getIsLogin()){
					message = null;
					removeFromSession(SESSION_MESSAGE_KEY);
				}
			}
		}
		if(null == page){
			page = PaginationFactory.getInstance().createPagination(getUserAgentType());
			page.setPageIndex(1);
			page.setPageSize(20);
		}
		
		checkIsOwner();
	}
	
	protected void checkIsOwner(){
		if(usr == null || usr == 0){
			if(getIsLogin()){
				usr = getUserid(); // 如果是登陆用户
			}
		}
		if(usr != null && usr.compareTo(getUserid()) == 0){
			isOwner = true;
		}else{
			isOwner = false;
		}
	}
	protected void addMessage(int position, String message){
		Message m = new Message(String.valueOf(position), message);
		MessageManager.addMessage(getUserid(), m);
	}
	protected void addFiledError(String fieldName, String message){
		FieldError fieldError = new FieldError(fieldName, message);
		MessageManager.addFieldError(getUserid(), fieldError);
	}
	
	/**
	 * 保存到session attribute中
	 */
	protected void setToSession(String key, Object obj){
		getSession().setAttribute(key, obj);
	}
	/**
	 * 从session attribute中获得数据，同时删除SESSION中的此信息
	 */
	protected Object removeFromSession(String key){
		Object obj = getSession().getAttribute(key);
		getSession().removeAttribute(key);
		return obj;
	}
	/**
	 * 从session attribute中获得数据，此信息依然存在SESSION中
	 */
	protected Object getFromSession(String key){
		return getSession().getAttribute(key);
	}
    /**
     * Convenience method to get the request
     * @return current request
     */
    protected HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    /**
     * Convenience method to get the response
     * @return current response
     */
    protected HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * Convenience method to get the session. This will create a session if one doesn't exist.
     * @return the session from the request (request.getSession()).
     */
    protected HttpSession getSession() {
        return getRequest().getSession();
    }

	public UserAgentBean getUserAgentBean() {
		return userAgentBean;
	}

	public void setUserAgentBean(UserAgentBean bean) {
		this.userAgentBean = bean;
	}
	
	public String getUserAgentType() {
		return userAgentType;
	}
	
	public void setUserAgentType(String userAgentType) {
		this.userAgentType = userAgentType;
	}

	public OnlineUser getOnlineUser() {
		return onlineUser;
	}

	public void setOnlineUser(OnlineUser onlineUser) {
		this.onlineUser = onlineUser;
	}

	public boolean getIsLogin() {
		if(getRole() == OnlineUser.USER_ROLE_ANONYMOUS){
			return false;
		}else{
			return true;
		}
	}

	private int getRole(){
		return getOnlineUser().getRole();
	}

	public String getPi() {
		return pi;
	}

	public void setPi(String pi) {
		this.pi = pi;
	}

	public String getGotoUrl() {
		return gotoUrl;
	}

	public void setGotoUrl(String gotoUrl) {
		this.gotoUrl = gotoUrl;
	}
	public Long getUserid() {
		return userid;
	}

	public void setUserid(Long userid) {
		this.userid = userid;
	}

	public String getNickname() {
		UserManager userManager = (UserManager) ApplicationManager.appContext.getBean("userManager");
		return userManager.getByUserid(onlineUser.getUserid()).getNickname();
//		return onlineUser.getUserInfo().getNickname();
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public Long getUsr() {
		return usr;
	}

	public void setUsr(Long usr) {
		this.usr = usr;
	}

	public PaginationSupport getPage() {
		return page;
	}

	public void setPage(PaginationSupport page) {
		this.page = page;
	}

	public Integer getDirect() {
		return direct;
	}

	public void setDirect(Integer direct) {
		this.direct = direct;
	}

	public boolean getIsOwner() {
		return isOwner;
	}

	public void setIsOwner(boolean isOwner) {
		this.isOwner = isOwner;
	}
	
	public UserInfo getUserInfo() {
		return userInfo;
	}

	public void setUserInfo(UserInfo userInfo) {
		this.userInfo = userInfo;
	}

	public UserProfile getUserProfile() {
		return userProfile;
	}

	public void setUserProfile(UserProfile userProfile) {
		this.userProfile = userProfile;
	}
}
